/*
 * @Descripttion: redisConfig
 * @version: 1.0
 * @Author: hzj-1510017964@qq.com
 * @Date: 2020-04-22 14:50:26
 * @LastEditors: hzj-1510017964@qq.com
 * @LastEditTime: 2020-05-06 11:12:54
 */
const Redis = require('redis')   //安装redis

//连接redis
let client = Redis.createClient()

//监听redis
client.on('error', function (err) {
    console.log('redis 连接失败' + err);
});
client.on('connect', function () {
    console.log('redis连接成功...')
});


/**
 * set 设置值
 * dbNum redis库编号
 * key 键
 * value 值
 * expire 过期时间
 * callback 回调函数
 */
const set = (dbNum, key, value, expire) => {
    return new Promise((resolve, reject) => {
        client.select(dbNum, err => {
            if (err) {
                reject(err)
            } else {
                client.set(key, value, (err, res) => {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(res)
                    }
                })
                if (expire) {
                    client.expire(key, expire)
                }
            }
        })

    })
}


const get = (dbNum, key) => {
    return new Promise((resolve, reject) => {
        client.select(dbNum, err => {
            if (err) {
                reject(`redis get 选库失败：${err}`)
            } else {
                client.get(key, (err, res) => {
                    if (err) {
                        reject(`edis获取失败：${err}`)
                    } else {
                        resolve(res)
                    }
                })
            }
        })
    })
};



module.exports = {
    set,
    get
}